package executor;

import basic.JodisDb;
import protocol.ErrorResponse;
import protocol.ProtocolConstant;
import protocol.Request;
import protocol.Response;

import java.util.HashMap;
import java.util.Map;

/**
 * 执行器工厂类，负责选择具体的执行器进行调度
 * **/
public class ExecutorFactory {


    //利用策略模式解决if else太多的问题
    private Map<String,Executor> executorMap = new HashMap<>();

    public ExecutorFactory(JodisDb jodisDb) {
        StringExecutor stringExecutor = new StringExecutor(jodisDb);
        //string命令对应的执行器
        for(String cmd : ProtocolConstant.STRING_CMDS){
            executorMap.put(cmd,stringExecutor);
        }
    }

    public Response execute(Request request){
        String command = request.getCommand();
        // 判断解析请求中是否存在错误
        if (request.isError()) {
            return request.errorResponse();
        }
        Response response;

        if(executorMap.containsKey(command)){
            response = executorMap.get(command).execute(request);
        }else{
            // cmd is unknown
            response = ErrorResponse.errorUnknownCmd(command);
        }

        return response;
    }
}
